<template>
    <section class="content">
        <div class="section-block">
            <div class="step-block">
                <Steps :current="step" style="width:800px;text-align:center">
                    <Step :title="$t('langObj.courseInfo')" v-if="current === 0"></Step>
                    <Step :title="$t('langObj.dataInfo')" v-if="current === 0 || current === 1"></Step>
                    <Step :title="$t('langObj.machineInfo')" v-if="current === 0 || current === 1 || current === 2" ></Step>
                    <Step :title="$t('langObj.order')"></Step>
                </Steps>
            </div>
            <div class="buy-goods-info" v-if="(current+step) === 0">
                <div class="goods-title">|&nbsp;{{ $t('langObj.buyCourse') }}</div>
                <p>{{ $t('langObj.courseTime') }}<span>{{ startTime }} - {{ endTime }}</span></p>
                <p>{{ $t('langObj.courseName') }}<span>{{ courseInfo.name }}</span></p>
                <img :src="courseInfo.imagePath" width="124px" height="78px" style="margin-left:50px">
                <div class="conicnt-balance">
                    <p>{{ $t('langObj.accountBalance') }}<span>{{ balance }}</span></p>
                </div>
                <p>{{ $t('langObj.coursePrice') }}<span>{{ courseInfo.coinCnt }} {{ $t('langObj.coupon') }}</span></p>
                <p>{{ $t('langObj.pay') }}<span>{{ courseInfo.coinCnt }} {{ $t('langObj.coupon') }}</span></p>
            </div>
            <div class="buy-goods-info" v-if="(current+step) === 1">
                <div class="goods-title">|&nbsp;{{ $t('langObj.dataSetDesc') }}</div>
                <p>{{ $t('langObj.dataSetName') }}<span>{{ datalabInfo.name }}</span></p>
                <img :src="datalabInfo.image" width="124px" height="78px" style="margin-left:50px">
                <p>{{ $t('langObj.usedTime') }}<span>{{ beginTime }} - {{ dataEndTime }}</span></p>
                <div class="conicnt-balance">
                    <p>{{ $t('langObj.accountBalance') }}<span>{{ balance }}</span></p>
                </div>
                <p>{{ $t('langObj.dataSetPrice') }}<span>{{ datalabInfo.coinCnt }} {{ $t('langObj.coupon') }}</span></p>
            </div>
            <div class="buy-goods-info" v-if="(current+step) === 2">
                <div>
                    <div class="goods-title">|&nbsp;{{ projectInfo.resource_price_id ? $t('langObj.xufei'): $t('langObj.pro')}}</div>
                    <Form :label-width="120" ref="formValidate" :model="projectInfo" :rules="ruleValidate">
                        <FormItem :label="$t('langObj.projectName')" prop="name">
                            <Input v-if="projectInfo.resource_price_id" readonly v-model="projectInfo.name" style="width:400px"/>
                            <Input v-else v-model="projectInfo.name" style="width:400px" />
                        </FormItem>
                        <FormItem :label="$t('langObj.projectDesc')" prop="taskDesc">
                            <Input v-if="projectInfo.resource_price_id" readonly v-model="projectInfo.taskDesc" style="width:400px" type="textarea" :rows="4" />
                            <Input v-else v-model="projectInfo.taskDesc" style="width:400px" type="textarea" :rows="4" placeholder="不超过140字符" />
                        </FormItem>
                        <FormItem label="Notebook" v-if="!projectInfo.resource_price_id">
                            <Radio v-model="projectInfo.machine">Jupyter</Radio>
                        </FormItem>
                        <FormItem :label="$t('langObj.machine')">
                            <div v-if="queryType === 'course' || (current === 2 && renew === 1)" class="machine-list">
                                <div class="activeIndex">
                                    {{projectInfo.cpu}}Core + {{ projectInfo.memory }}Gi
                                </div>
                            </div>
                            <div v-else class="machine-list">
                                <div v-for="item in machineList" :key="item.id" @click="changeMachine(item.id)" :class="activeIndex === item.id ? 'activeIndex':'' ">
                                    {{item.cpu}}Core + {{ item.memory }}Gi
                                </div>
                            </div>
                        </FormItem>
                        <FormItem :label="$t('langObj.storage')">
                            <Input v-if="queryType === 'course' || (current === 2 && renew === 1)" readonly v-model="projectInfo.storage" style="width:400px" />
                            <InputNumber v-else :min="1" v-model="projectInfo.storage"></InputNumber>Gi
                        </FormItem>
                        <FormItem :label="$t('langObj.time')">
                             <InputNumber :min="1" v-model="projectInfo.selectTime"></InputNumber>{{ $t('langObj.hour') }}
                        </FormItem>
                    </Form>
                    <div class="conicnt-balance">
                        <p>{{ $t('langObj.accountBalance') }}<span>{{ balance }}</span></p>
                    </div>
                    <p>{{ $t('langObj.machinePrice') }}<span>{{ defaultCoinCnt/projectInfo.selectTime }} {{ $t('langObj.coupon') }}/{{ $t('langObj.hour') }}</span></p>
                    <p>{{ $t('langObj.count') }}<span>{{ projectInfo.selectTime }} {{ $t('langObj.hour') }}</span></p>
                    <p>{{ $t('langObj.pay') }}<span>{{ defaultCoinCnt }} {{ $t('langObj.coupon') }}</span></p>
                </div>    
            </div>
            <div class="buy-goods-info order-list-block" v-if="(current+step) === 3">
                <div>
                    <div class="goods-title">|&nbsp;{{ $t('langObj.orderInfo') }}</div>
                    <p>{{ $t('langObj.orderNum') }}<span>{{ orderInfo.orderNum }}</span></p>
                    <p>{{ $t('langObj.orderTime') }}<span>{{ createTime }}</span></p>
                </div>
                <div v-if="Object.keys(courseParams).length !== 0">
                    <div class="goods-title">|&nbsp;{{ $t('langObj.courseInfo') }}</div>
                    <p>{{ $t('langObj.courseTime') }}<span>{{ startTime }} - {{ endTime }}</span></p>
                    <p>{{ $t('langObj.courseName') }}<span>{{ courseInfo.name }}</span></p>
                    <img :src="courseInfo.imagePath" width="124px" height="78px" style="margin-left:50px">
                    <p>{{ $t('langObj.coursePrice') }}<span>{{ courseInfo.coinCnt }}{{$t('langObj.coupon') }}</span></p>
                </div>
                <div v-if="Object.keys(datalabaParams).length !== 0">
                    <div class="goods-title">|&nbsp;{{ $t('langObj.dataInfo') }}</div>
                    <p>{{ $t('langObj.dataSetName') }}<span>{{ datalabInfo.name }}</span></p>
                    <img :src="datalabInfo.image" width="124px" height="78px" style="margin-left:50px">
                    <p>{{ $t('langObj.dataSetPrice') }}<span>{{ datalabInfo.coinCnt }}{{$t('langObj.coupon') }}</span></p>
                </div>
                <div v-if="Object.keys(projectParams).length !== 0">
                    <div class="goods-title">|&nbsp;{{ $t('langObj.machineInfo') }}</div>
                    <p>{{ $t('langObj.cpu') }}<span>{{ machineParams.cpu }}Core</span></p>
                    <p>{{ $t('langObj.memory') }}<span>{{ machineParams.memory }}Gi</span></p>
                    <p>{{ $t('langObj.storage') }}<span>{{ projectInfo.storage }}Gi</span></p>
                    <p>{{ $t('langObj.time') }}<span>{{ projectInfo.selectTime }}{{ $t('langObj.hour') }}</span></p>
                    <p>{{ $t('langObj.pay') }}<span>{{ defaultCoinCnt }}{{$t('langObj.coupon')}}</span></p>
                </div>
                <div>
                    <div class="goods-title">|&nbsp;{{ $t('langObj.payInfo') }}</div>
                    <p v-if="Object.keys(courseParams).length !== 0">{{ $t('langObj.coursePrice') }}<span>{{ courseInfo.coinCnt }}{{$t('langObj.coupon')}}</span></p>
                    <p v-if="Object.keys(datalabaParams).length !== 0">{{ $t('langObj.dataSetPrice') }}<span>{{ datalabInfo.coinCnt }}{{$t('langObj.coupon')}}</span></p>
                    <p v-if="Object.keys(projectParams).length !== 0">{{ $t('langObj.machinePrice') }}<span>{{ defaultCoinCnt }}{{$t('langObj.coupon')}}</span></p>
                    <div class="conicnt-balance">
                        <p>{{$t('langObj.accountBalance')}}<span>{{ balance }}{{$t('langObj.coupon')}}</span></p>
                    </div>
                    <p>{{$t('langObj.pay')}}<span>{{ orderInfo.orderCoin }}{{$t('langObj.coupon')}}</span></p>
                </div>
                <div class="pay-verification">
                    <div class="goods-title">|&nbsp;{{ $t('langObj.verfiyInfo') }}</div>
                    <div>
                        <p style="display:inline-block">{{ $t('langObj.verfiy') }}
                            <Button style="margin:0 20px"><Icon type="ios-tablet-portrait" />{{ $t('langObj.phone') }}</Button>
                            <Button class="activeIndex"><Icon type="ios-mail-outline" />{{ $t('langObj.email') }}</Button>
                        </p>
                    </div>
                    <p style="color:rgba(102,102,102,1);font-size:12px;">{{ checkEmail }}</p>
                    <p>
                        <Input v-model="checkCode" :placeholder="$t('langObj.inputCode')" style="width:200px"/>
                        <Button type="primary" v-show="show" @click="getVerificationCode">{{ $t('langObj.verefiyCode') }}</Button>
                        <Button style="width:92px" v-show="!show" disabled>{{ timeCount }}s</Button>
                    </p>
                    <p>
                        <Button type="primary" @click="sureBuy">{{ $t('langObj.buy') }}</Button>
                    </p>
                </div>
            </div>
            <div class="button-block">
                <Button type="error" @click="delayBuy">{{ $t('langObj.exitOrder') }}</Button>
                <Button type="primary" @click="noBuyNext" v-if="step !== 0 && (step + current) < 3">{{ $t('langObj.nobuy') }}</Button>
                <Button type="primary" @click="buyNext" v-if="(step + current) < 3">{{ $t('langObj.buy') }}</Button>
            </div>
        </div>
    </section>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import { formatData } from '@/utils/format';
export default {
    beforeRouteEnter (to, from, next) {
        next(vm => {
           vm.refer = from.path
        })  
    },
    data() {
        return {
            current:Number(this.$route.params.current),
            id:Number(this.$route.params.id),
            renew:Number(this.$route.params.renew),
            queryType:this.$route.query.type,
            step:0,
            ruleValidate: {
                name: [
                    { required: true, message: 'The name cannot be empty', trigger: 'blur' }
                ],
                taskDesc: [
                    { required: true, message: 'The desc cannot be empty', trigger: 'blur' }
                ],
            },
            courseInfo:{},
            datalabIsBuy:false,
            datalabInfo:{},
            machineList:[],
            projectInfo:{
                name:"",
                taskDesc:"",
                machine:true,
                storage:2,
                selectTime:1,
            },
            activeIndex:1,
            defaultCoinCnt:null,
            machineParams:{},
            // 缓存购买信息
            resourceList:[],
            courseParams:{},
            datalabaParams:{},
            projectParams:{},
            orderInfo:{},
            checkEmail:localStorage.getItem("email"),
            checkCode:"",
            timeCount:"",
            show:true,
        }
    },
    computed: {
        ...mapGetters({
            balance:'balance'
        }),
        startTime(){
            return formatData(this.courseInfo.startTime)
        },
        endTime(){
            return formatData(this.courseInfo.endTime)
        },
        beginTime(){
            return formatData(this.datalabInfo.beginTime,{type:"detail"})
        },
        dataEndTime(){
            return formatData(this.datalabInfo.endTime,{type:"detail"})
        },
        createTime(){
            return formatData(this.orderInfo.createTime,{type:"detail"})
        },
        listenerMachine(){
            return{
                resourcePriceId:this.activeIndex,
                storage:this.projectInfo.storage,
                time:this.projectInfo.selectTime
            }
        }
    },
    watch: {
        listenerMachine(){
            this.XpriceCalculate({
                resourcePriceId:this.activeIndex,
                storage:this.projectInfo.storage || 2,
                time:this.projectInfo.selectTime || 1
            }).then(res => {
                this.defaultCoinCnt = res.data
            })
        }
    },
    methods: {
        ...mapActions(['XuserBalance','XgetCoursePrice','XbuyNotebook','XcheckDatalabIsBuy','XgetBuyDatalabInfo','XgetAllMachine','XrenewalFeeInfo','XseletedMachine','XpriceCalculate','XbuyReasource','XconsumeCode','XsureBuy']),
        // 不购买数据集或者机器直接调跳入订单
        noBuyNext(){
           this.step = 3 - this.current;
            // 获取订单号
            this.XbuyReasource({
                coinsRequestList:this.resourceList
            }).then(res => {
                this.orderInfo = res.data
            }).catch(err => {
                this.$Message.error(err.response.data.message)
            })
        },
        buyNext(){
            // 已经购买了数据集直接跳入订单页面
            if(this.datalabIsBuy){
                this.noBuyNext()
            }else{
                this.step++;
                // 教育平台购买进入=》下一步到数据集购买
                if(this.step + this.current === 1){
                    this.XgetBuyDatalabInfo({
                        courseId:this.id,
                        dataId:0
                    }).then(res => {
                        this.datalabInfo = res.data
                    })
                    // 教育平台购买进入=》下二步到机器购买 或者 数据集购买进入=》下一步到机器购买
                }else if(this.step + this.current === 2){
                    // 生成订单号数据集参数
                    this.datalabaParams = {
                        param:{
                            dataId:this.datalabInfo.id,
                            renew:this.renew
                        },
                        type:2
                    };
                    this.resourceList.push(this.datalabaParams)

                    this.XgetAllMachine().then(res => {
                        this.machineList = res.data;
                        this.XpriceCalculate({
                            resourcePriceId:this.activeIndex,
                            storage:this.projectInfo.storage,
                            time:this.projectInfo.selectTime
                        }).then(res => {
                            this.defaultCoinCnt = res.data
                        })
                    })
                }else if(this.step + this.current === 3){
                    
                        if (this.projectInfo.name && this.projectInfo.taskDesc) {
                            // 订单页面机器配置信息
                            this.XseletedMachine(this.activeIndex).then(res => {
                                this.machineParams = res.data
                            })
                            // 生成订单号机器参数
                            this.projectParams = {
                                param:{
                                    time:this.projectInfo.selectTime,
                                    renew:this.renew,
                                    resourcePriceId:this.activeIndex,
                                    storage:this.projectInfo.storage,
                                    fromType:0,
                                    name:this.projectInfo.name,
                                    desc:this.projectInfo.taskDesc,
                                },
                                type:1
                            }
                            // 教育平台购买课程进入一直到购买机器 或者创建Notebook（订单号机器参数courseId）
                            if(this.current === 0 || this.queryType === "course"){
                                this.projectParams.param.courseId = this.id
                            } 
                            // 教育平台创建Notebook(订单号机器参数fromType)
                            if(this.current === 2 && this.queryType === "course"){
                                this.projectParams.param.fromType = 1
                            }
                            // 数据集购买或者续费进入一直到购买机器 或者创建项目（订单号机器参数datasetId）
                            if(this.current === 1 || this.queryType === "datalab"){
                                this.projectParams.param.datasetId = this.id
                            }
                            // 我的项目续费机器（订单号机器参数taskId）
                            if(this.current === 2 && this.renew === 1){
                                this.projectParams.param.taskId = this.id
                            }
                            // 数据集续费的时候（订单号机器参数renew）
                            if(this.current !== 2){
                                this.projectParams.param.renew = 0
                            }
                            this.resourceList.push(this.projectParams);
                            // 获取订单信息
                            this.XbuyReasource({
                                coinsRequestList:this.resourceList
                            }).then(res => {
                                this.orderInfo = res.data
                            }).catch(err => {
                                this.$Message.error({
                                    content:err.response.data.message,
                                    duration:3
                                })
                            })
                        } else {
                            this.$Message.error({
                                content:"参数错误",
                                duration:3
                            })
                            this.step--;
                        }
                    
                }
            }
         },
         delayBuy(){
            this.$router.push({path:this.refer?this.refer:'/'})
         },
         changeMachine(id){
             this.activeIndex = id;
         },
         getVerificationCode(){
            const TIME_COUNT = 60;
            if(!this.timer){
                this.timeCount = TIME_COUNT;
                this.show = false;
                this.timer = setInterval(() => {
                    if(this.timeCount > 0 && this.timeCount <= TIME_COUNT){
                        this.timeCount--
                    }else{
                        this.show = true;
                        clearInterval(this.timer);
                        this.timer = null;
                    }
                },1000)
            }
            this.XconsumeCode().then(res => {
                this.$Message.success("验证码发送成功")
            })
        },
        sureBuy(){
            this.XsureBuy({
                checkCode:this.checkCode,
                orderNum:this.orderInfo.orderNum,
                userEmail:this.checkEmail
            }).then(res => {
                this.$Message.success("购买成功");
                this.$router.push({path:this.refer?this.refer:'/'})
            }).catch(err => {
                this.$Message.error({
                    content:err.response.data.message,
                    duration:3
                })
            })
        }
    },
    mounted(){
        this.XuserBalance();
        // 教育平台购买进入
        if(this.current === 0){
            this.XcheckDatalabIsBuy(this.id).then(res => {
                this.datalabIsBuy = res.data
            })
            this.XgetCoursePrice(this.id).then(res => {
                this.courseInfo = res.data;
                // 生成订单课程参数
                this.courseParams = {
                    sourceId:this.courseInfo.id,
                    type:0
                };
                this.resourceList.push(this.courseParams)
            })
            
        // 数据集续费进入
        }else if(this.current === 1){
            this.XgetBuyDatalabInfo({
                courseId:0,
                dataId:this.id
            }).then(res => {
                this.datalabInfo = res.data
            })

        // 我的项目续费进入 或者 数据集创建项目进入 或者 教育平台创建Notebook
        }else if(this.current === 2){
            // 续费
            if(this.renew === 1){
                this.XrenewalFeeInfo(this.id).then(res => {
                    if(res.data.resource_price_id){
                        this.XseletedMachine(res.data.resource_price_id).then(val => {
                            this.projectInfo = Object.assign(this.projectInfo,res.data,val.data);
                            this.XpriceCalculate({
                                resourcePriceId:val.data.id,
                                storage:this.projectInfo.storage,
                                time:this.projectInfo.selectTime
                            }).then(ele =>{
                                this.defaultCoinCnt = ele.data
                            })
                        })
                    }
                })
            }else{
                // 教育平台创建Notebook
                if (this.queryType === 'course'){
                    this.XbuyNotebook().then(res => {
                        if(res.data.resourcePricesId){
                            this.XseletedMachine(res.data.resourcePricesId).then(val => {
                                this.projectInfo = Object.assign(this.projectInfo,res.data,val.data);
                                this.XpriceCalculate({
                                    resourcePriceId:val.data.id,
                                    storage:this.projectInfo.storage,
                                    time:this.projectInfo.selectTime
                                }).then(ele =>{
                                    this.defaultCoinCnt = ele.data
                                })
                            })
                        }
                    })
                }else{
                     // 数据集创建项目
                    this.XgetAllMachine().then(res => {
                        this.machineList = res.data;
                        this.XpriceCalculate({
                            resourcePriceId:this.activeIndex,
                            storage:this.projectInfo.storage,
                            time:this.projectInfo.selectTime
                        }).then(res => {
                            this.defaultCoinCnt = res.data
                        })
                    })
                }
            }
        }
        
    }
}
</script>

<style lang="scss">
    .step-block{
        .ivu-steps .ivu-steps-tail{
            display: none;
        }
    }
</style>

<style lang="scss" scoped>
    .content{
        flex:1;
        min-width: 1200px;
        padding: 20px;
        background-color:#f9fafa;

        .section-block{
            width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
        }
        .step-block{
            height: 130px;
            border-bottom: 1px solid #f7f7f7;
            display: flex;
            align-items: center;
            justify-content: center;
            
        }

        .buy-goods-info{
            font-size:12px;
            font-weight:400;
            color:rgba(51,51,51,1);

            p{
                margin:20px 50px;
            }
            span{
                margin-left:15px;
            }
            .goods-title{
                font-size:16px;
                font-weight:bold;
                color:rgba(51,51,51,1);
                margin:50px;
            }
            .conicnt-balance{
                height:40px;
                line-height: 40px;
                background:rgba(237,238,243,1);
                font-size:12px;
                font-weight:bold;
                color:rgba(243,101,57,1);
            }
        }
        
        .machine-list{
            display: flex;
            align-items: center;
            div{
                width:110px;
                height:32px;
                border:1px solid rgba(211, 217, 223, 1);
                border-radius:6px;
                text-align: center;
                cursor: pointer;
            }
            div + div{
                margin-left:15px;
            }
        }
        .activeIndex{
            background:#68AAFD;
            color: #fff;
        }
        .order-list-block{
            & > div{
                border-bottom:1px solid rgba(211,217,223,1);
            }
        }
        .button-block{
            margin-top:50px;
            text-align: center;
            button + button{
                margin-left:15px;
            }
        }
    }
</style>
